package com.dylan.shot.head.shiro;

import com.dylan.shot.common.model.Member;
import com.dylan.shot.head.service.MemberAuthenticateService;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Created by Dylan on 2017/9/11.
 */
public class MyUserFilter extends UserFilter {
    private Logger LOG = LoggerFactory.getLogger(getClass());

    private MemberAuthenticateService memberAuthenticateService;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = getSubject(request, response);
            if (subject.isAuthenticated()) {
                return true;
            }
            Object principal = subject.getPrincipal();
            // If principal is not null, then the user is known and should be allowed access.
            if (principal != null) {
                Member member = ShiroHelper.getCachedMember();
                // 获取用户信息
                if (member == null) {
                    LOG.info("用户信息为空,通过username获取用户信息:{}", principal);
                    member = memberAuthenticateService.getMemberByUsername(String.valueOf(principal));
                }
                if (member == null) {
                    LOG.info("用户信息为空,通过手机号获取用户信息:{}", principal);
                    member = memberAuthenticateService.getMemberByPhone(String.valueOf(principal));
                }
                if (member == null) {
                    LOG.info("用户信息为空,通过邮箱获取用户信息:{}", principal);
                    member = memberAuthenticateService.getMemberByEmail(String.valueOf(principal));
                }
                if (member == null) {
                    LOG.info("始终无法获取用户信息");
                    return false;
                } else {
                    member.setPassword(null);
                    ShiroHelper.setCachedMember(member);
                    return true;
                }
            }
            return false;
        }
    }

    public void setMemberAuthenticateService(MemberAuthenticateService memberAuthenticateService) {
        this.memberAuthenticateService = memberAuthenticateService;
    }
}
